#!/bin/sh

# ========================
#  LED 控制脚本 (BusyBox 兼容)
# ========================

# --- 硬件寄存器初始化 ---
# 如果 bspmm 不可用或失败，忽略（仅警告）
bspmm() {
    /usr/bin/bspmm "$@" >/dev/null 2>&1 || return 1
}

# 执行寄存器设置（按需调整路径）
bspmm 0x010260064 0x1611 || echo "Warning: bspmm 0x010260064 failed"
bspmm 0x010260058 0x1201 || echo "Warning: bspmm 0x010260058 failed"
bspmm 0x010260068 0x1301 || echo "Warning: bspmm 0x010260068 failed"
bspmm 0x010260060 0x1301 || echo "Warning: bspmm 0x010260060 failed"
bspmm 0x010260078 0x1201 || echo "Warning: bspmm 0x010260078 failed"

# --- LED GPIO 定义 ---
# 使用变量存储 GPIO 编号
LED1_GREEN=39
LED2_YELLOW=36
LED3_GREEN=40
LED4_RED=38
LED5_YELLOW=43

# --- 延时设置 ---
DELAY=0.2

# --- GPIO 操作函数 ---
export_gpio() {
    local gpio=$1
    # 尝试导出，如果已存在则忽略错误
    echo "$gpio" > /sys/class/gpio/export 2>/dev/null || true
}

set_direction() {
    local gpio=$1
    echo "out" > "/sys/class/gpio/gpio${gpio}/direction" 2>/dev/null || \
        echo "Failed to set direction for GPIO $gpio"
}

set_value() {
    local gpio=$1
    local value=$2
    echo "$value" > "/sys/class/gpio/gpio${gpio}/value" 2>/dev/null || \
        echo "Failed to set value $value for GPIO $gpio"
}

# --- 所有 LED 列表（用于循环）---
# 将所有 GPIO 编号放入一个列表（空格分隔）
LED_LIST="$LED1_GREEN $LED2_YELLOW $LED3_GREEN $LED4_RED $LED5_YELLOW"

# --- 初始化 GPIO ---
echo "Initializing LEDs... Press Ctrl+C to stop."

for gpio in $LED_LIST; do
    export_gpio "$gpio"
    set_direction "$gpio"
done

# --- 心跳效果 ---
heartbeat() {
    while true; do
        for gpio in $LED_LIST; do
            set_value "$gpio" 1
            sleep "$DELAY"
            set_value "$gpio" 0
            sleep "$DELAY"
        done

         for gpio in $LED_LIST; do
            set_value "$gpio" 1
            sleep "$DELAY"
        done

         for gpio in $LED_LIST; do
            set_value "$gpio" 0
            sleep "$DELAY"
        done
    done
}

# --- 信号处理：清理 GPIO ---
# 定义清理函数（关闭所有 LED）
cleanup() {
    echo ""
    echo "Signal received. Turning off all LEDs..."
    for gpio in $LED_LIST; do
        set_value "$gpio" 0
    done
    sleep 0.1
    echo "Cleanup done. Exiting."
    exit 0
}

# 捕获中断信号（Ctrl+C）和终止信号
trap cleanup INT TERM

# --- 启动心跳 ---
heartbeat

# 正常情况下不会到这里
exit 0
